<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="起始分数" prop="startScore">
        <el-input
          v-model="queryParams.startScore"
          placeholder="请输入起始分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="截至分数" prop="endScore">
        <el-input
          v-model="queryParams.endScore"
          placeholder="请输入截至分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="级别名称" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入级别名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="级别描述" prop="levelDesc">-->
<!--        <el-input-->
<!--          v-model="queryParams.levelDesc"-->
<!--          placeholder="请输入级别描述"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="删除标识,未删除为0，已删除为1" prop="deleteFlag">-->
<!--        <el-input-->
<!--          v-model="queryParams.deleteFlag"-->
<!--          placeholder="请输入删除标识,未删除为0，已删除为1"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="版本号" prop="version">-->
<!--        <el-input-->
<!--          v-model="queryParams.version"-->
<!--          placeholder="请输入版本号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:level:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:level:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:level:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:level:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="级别id" align="center" prop="levelId" />
      <el-table-column label="起始分数" align="center" prop="startScore" />
      <el-table-column label="截至分数" align="center" prop="endScore" />
      <el-table-column label="级别名称" align="center" prop="levelName" />
      <el-table-column label="级别描述" align="center" prop="levelDesc" />
<!--      <el-table-column label="删除标识" align="center" prop="deleteFlag" />-->
<!--      <el-table-column label="版本号" align="center" prop="version" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:level:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:level:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改运动级别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="起始分数" prop="startScore">
          <el-input v-model="form.startScore"
                    placeholder="请输入起始分数"
                    @change="validateEndScore" />
        </el-form-item>
        <el-form-item label="截至分数" prop="endScore">
          <el-input v-model="form.endScore" placeholder="请输入截至分数" />
        </el-form-item>
        <el-form-item label="级别名称" prop="levelName">
          <el-input v-model="form.levelName" placeholder="请输入级别名称" />
        </el-form-item>
        <el-form-item label="级别描述" prop="levelDesc">
          <el-input v-model="form.levelDesc" placeholder="请输入级别描述" />
        </el-form-item>
<!--        <el-form-item label="删除标识" prop="deleteFlag">-->
<!--          <el-input v-model="form.deleteFlag" placeholder="请输入删除标识,未删除为0，已删除为1" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="版本号" prop="version">-->
<!--          <el-input v-model="form.version" placeholder="请输入版本号" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLevel, getLevel, delLevel, addLevel, updateLevel } from "@/api/system/level"

export default {
  name: "Level",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 运动级别表格数据
      levelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startScore: null,
        endScore: null,
        levelName: null,
        levelDesc: null,
        deleteFlag: null,
        version: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // 起始分数：必填 + 必须是数字
        startScore: [
          { required: true, message: "请输入起始分数", trigger: "blur" },
          {
            type: "number",
            message: "起始分数必须为有效数字",
            trigger: "blur",
            transform: (value) => Number(value)  // 转换输入为数字，避免字符串数字校验失败
          }
        ],
        // 截止分数：必填 + 数字 + 自定义交叉校验（起始≤截止）
        endScore: [
          { required: true, message: "请输入截至分数", trigger: "blur" },
          {
            type: "number",
            message: "截至分数必须为有效数字",
            trigger: "blur",
            transform: (value) => Number(value)
          },
          {
            // 自定义校验：比较起始分数和截止分数
            validator: function(rule, value, callback) {
              const start = Number(this.form.startScore); // 起始分数转数字
              const end = Number(value); // 当前截止分数转数字

              // 校验条件：起始分数已填写 + 两者都是有效数字 + 起始>截止
              if (
                this.form.startScore !== null &&
                this.form.startScore !== "" &&
                !isNaN(start) &&
                !isNaN(end) &&
                start > end
              ) {
                callback(new Error("分数范围输入有误，请重新输入")); // 触发错误提示
              } else {
                callback(); // 校验通过
              }
            }.bind(this), // 绑定this，确保能访问到form数据
            trigger: ["blur", "change"] // 失去焦点/值变化时都校验
          }
        ],
        // 级别名称：必填（可选，增强表单完整性）
        levelName: [
          { required: true, message: "请输入级别名称", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 新增：起始分数变化时，手动校验截止分数（覆盖先输截止分数的场景）
    validateEndScore() {
      if (this.$refs.form) {
        this.$refs.form.validateField("endScore"); // 触发单个字段校验
      }
    },
    /** 查询运动级别列表 */
    getList() {
      this.loading = true
      listLevel(this.queryParams).then(response => {
        this.levelList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        levelId: null,
        startScore: null,
        endScore: null,
        levelName: null,
        levelDesc: null,
        createTime: null,
        updateTime: null,
        deleteFlag: null,
        createBy: null,
        updateBy: null,
        version: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.levelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加运动级别"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const levelId = row.levelId || this.ids
      getLevel(levelId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改运动级别"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.levelId != null) {
            updateLevel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLevel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const levelIds = row.levelId || this.ids
      this.$modal.confirm('是否确认删除运动级别编号为"' + levelIds + '"的数据项？').then(function() {
        return delLevel(levelIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/level/export', {
        ...this.queryParams
      }, `level_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
